package cn.vc.auth.interceptor;

import cn.vc.auth.entity.po.VUser;
import cn.vc.basicmodule.entity.Result;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ControllerInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
        //查询请求类型，如果只是GET请求，则全部放行
        String method = request.getMethod();
        if (method.equals("GET")) {
            return true;
        } else if (method.equals("POST")){
            return true;
        }
        HttpSession session = request.getSession();
        // 先从session域获取用户信息
        VUser myVUser = (VUser) session.getAttribute("myUser");
        if (myVUser == null) {
            // session域中不存在用户信息，通过token在缓存中查询用户信息
            String token = request.getHeader("token");
            System.out.println("token -> "+token);
            if (token==null) return false;
            String userJSON = stringRedisTemplate.opsForValue().get(token);
            System.out.println("json");
            if (userJSON==null) return false;
            myVUser = JSON.parseObject(userJSON, VUser.class);
            // 缓存中也不存在说明为未登录用户的非法操作
            if (myVUser == null) {
                log.info("拦截非法请求！");
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(new Result<>(0,"请勿发送非法请求！")));
                return false;
            }
            // 缓存中存在，可能为登录后首次请求，存入session中，存入redis中
            else {
                session.setAttribute("myUser", myVUser);
                stringRedisTemplate.opsForValue().set(token, JSON.toJSONString(myVUser), 60, TimeUnit.MINUTES);
                return true;
            }
        } else return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}
